package purchasePlan

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"github.com/zeromicro/go-zero/core/logx"
	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"
	"insighttracking/common/enum"
	"insighttracking/query/dao"
	"insighttracking/query/model"
	"insighttracking/query/service"
	"net/http"
	"os"
)

type CancelPurchasePlanApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewCancelPurchasePlanApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *CancelPurchasePlanApiLogic {
	hostname, _ := os.Hostname()
	return &CancelPurchasePlanApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *CancelPurchasePlanApiLogic) CancelPurchasePlanApi(req *types.CancelPurchasePlanReq) (resp string, err error) {
	planEntities, err := dao.PurchasePlanEntity.WithContext(l.ctx).Where(dao.PurchasePlanEntity.ID.In(req.IdList...)).Find()
	if err != nil || len(planEntities) == 0 {
		return "", errors.New("传递的主键错误")
	}
	for _, item := range planEntities {
		if item.Status != 0 {
			return "", errors.New("仅“待采购”且未关联订单的计划可取消")
		}
		// 如果关联了订单不可取消
		purchasePlanOrders, err := service.PurchasePlanOrdersService.GetByOrdersDetailByPlanIdApi(l.ctx, item.ID)
		if err != nil && len(purchasePlanOrders) > 0 {
			return "", errors.New("该采购计划已关联客户订单，不可取消！")
		}
	}

	// 事务开启
	tx := dao.Use(l.svcCtx.MysqlDb).Begin()
	// 取消采购计划
	if _, err = tx.PurchasePlanEntity.WithContext(l.ctx).Where(dao.PurchasePlanEntity.ID.In(req.IdList...)).UpdateSimple(
		dao.PurchasePlanEntity.Status.Value(30),
		dao.PurchasePlanEntity.CancelReason.Value(req.CancelReason),
	); err != nil {
		logx.Errorf("修改采购计划单状态失败:%v", err)
		if err = tx.Rollback(); err != nil {
			return "", err
		}
		return "", errors.New("取消失败")
	}

	// 订单详情改采购状态为取消采购
	planIdList := k.Map(planEntities, func(item *model.PurchasePlanEntity, index int) int64 {
		return item.ID
	})
	planOrdersEntities, err := service.PurchasePlanOrdersService.GetByOrdersDetailByPlanIdListApi(l.ctx, planIdList)
	if err == nil && len(planOrdersEntities) > 0 {
		orderSpuIdList := k.Map(planOrdersEntities, func(item *model.PurchasePlanOrdersEntity, index int) int64 {
			return item.OrdersSpuID
		})
		if _, err = tx.OrdersSpuEntity.WithContext(l.ctx).Where(dao.OrdersSpuEntity.ID.In(orderSpuIdList...)).UpdateSimple(
			dao.OrdersSpuEntity.PurchaseStatus.Value(enum.OrdersSpuPurchaseStatusCanceled),
		); err != nil {
			logx.Errorf("修改订单详情状态失败:%v", err)
			if err = tx.Rollback(); err != nil {
				return "", err
			}
			return "", errors.New("取消失败")
		}
	}
	if err = tx.Commit(); err != nil {
		return "", errors.New("取消失败")
	}
	return "取消成功", nil
}
